﻿Imports iTunesLib
Imports ITDETECTORLib
Imports System.Text
Imports System.Threading
Imports System.Drawing
Imports System.Drawing.Text



Public Class Main

#Region "screenResize"

    'Private Declare Function SetWindowPos Lib "user32.dll" Alias "SetWindowPos" (ByVal hWnd As IntPtr, ByVal hWndIntertAfter As IntPtr, ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal uFlags As Integer) As Boolean
    'Private Declare Function GetSystemMetrics Lib "user32.dll" Alias "GetSystemMetrics" (ByVal Which As Integer) As Integer
    'Private Const SM_CXSCREEN As Integer = 0
    'Private Const SM_CYSCREEN As Integer = 1
    'Private Shared HWND_TOP As IntPtr = IntPtr.Zero
    'Private Const SWP_SHOWWINDOW As Integer = 64

    'Public ReadOnly Property ScreenX() As Integer
    '    Get
    '        Return GetSystemMetrics(SM_CXSCREEN)
    '    End Get
    'End Property

    'Public ReadOnly Property ScreenY() As Integer
    '    Get
    '        Return GetSystemMetrics(SM_CYSCREEN)
    '    End Get
    'End Property

#End Region

    Private Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long

    Structure bums
        Dim Name As String
        Dim Artist As String
        Dim Cover As String
        Dim TrackTable() As iTunesLib.IITTrack
        Dim Year As String
    End Structure

#Region "declarations"


    Dim Albums(0) As bums
    Public WithEvents iTunesApp As iTunesLib.iTunesApp = Nothing
    Public mainLibrary As IITSource
    Public LibPlaylists As IITPlaylistCollection
    Public COMStateActive As Boolean = True

    Dim selectedAlbum As Integer
    Dim selectedTrack As Integer
    Dim blnShow As Boolean

    'settings
    Dim appDataPath As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    Dim appTitleForPath As String = "iTunesTouch"
    Dim imagePathFullsize As String = appDataPath & "\" & appTitleForPath & "\albumart\fullsize\"
    Dim imagePathThumbs As String = appDataPath & "\" & appTitleForPath & "\albumart\thumbs\"
    Dim appPath As String = "C:/"


    Public playListName As String = My.Settings.playlist '"iTunes DJ"
    Dim libraryName As String = My.Settings.library 'iTunes Library

    Dim cover_width As Integer = My.Settings.cover_width
    Dim cover_height As Integer = My.Settings.cover_height
    Dim trackTimer As Integer = 0

    Dim iTunesListener As New iTunesLib.iTunesApp
    Private WithEvents backgroundWorkerCovers As System.ComponentModel.BackgroundWorker
    Private WithEvents backgroundWorkerDrawer As System.ComponentModel.BackgroundWorker
    Dim todos As Integer = 0
    Public number_of_tracks As Integer

     

#End Region


#Region "loading stuff"

    Sub myTunes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Application.EnableVisualStyles()
        'Application.DoEvents()



        '
        ' Uses ITDetector to determine if iTunes is installed, seems to be new in v7 iTunes.
        '
        Dim iDetect As ITDETECTORLib.iTunesDetector = Nothing

        Try
            iDetect = New ITDETECTORLib.iTunesDetector
        Catch ex As Exception
            '
            ' Not bothered if iDetect not present, could be old version
            '
        End Try
        '
        ' If iDetect inialise did not fail use it to test for iTunes
        '
        If Not iDetect Is Nothing Then
            If iDetect.IsiTunesAvailable Then
                LoadFromiTunes()
            Else
                MsgBox("iTunes not installed, closing")
                Application.Exit()
            End If
        Else
            '
            ' iDetect not present try, maybe old version, try iTunes
            '
            'LoadFromiTunes()
        End If
    End Sub

    Sub LoadFromiTunes()
        '
        ' iTunes will start when iTunesApp initialised, if it is not already started,
        ' Minimise iTunes and set volume to 80, seems volume is per session and
        ' defaults to zero each time so you would have to remember it on exit and restore it
        ' each time, not bothered for the purpose of this exploratory app 80 will do.
        '
        Try
            iTunesApp = New iTunesLib.iTunesApp
        Catch ex As Exception
            MsgBox("Problem with iTunes" + vbCrLf + ex.Message)
        End Try

        If iTunesApp Is Nothing Then
            Application.Exit()
        Else
            mainLibrary = iTunesApp.LibrarySource
            LibPlaylists = mainLibrary.Playlists

            iTunesApp.BrowserWindow.Minimized = True
            iTunesApp.SoundVolume = 80
            'slVolume.Value = 80

            '======= LOAD SETTINGS
            If My.Settings.hide_mouse = 1 Then
                ShowCursor(False)
            End If
            Me.BackColor = My.Settings.bg_colour


            check_start_up()


            'show the loading doofa
            loadingPanel.Visible = True
            albumFlow.Visible = False

            loadPlaylist_iTunesDJ()
            updateTr()

            'Me.Show()
            'Me.Refresh()
            'Me.BringToFront()

            generate_no_cd_cover()


            'BuildPlayLists(LibPlaylists.Item(1))

            'start the background worker to get the album covers etc
            Dim Sources As IITSourceCollection
            Dim LibSource As IITSource

            Sources = iTunesApp.Sources
            LibSource = Sources.Item(1)
            number_of_tracks = LibSource.Playlists.Item(1).Tracks.Count
            albumLoadProgress.Maximum = number_of_tracks

            Me.DoubleBuffered = True
            backgroundWorkerAlbums.RunWorkerAsync()




        End If
    End Sub

#End Region

    Private Class updateStatus
        Public title As String
        Public counter As Integer

        Public Sub New(ByVal uTitle As String, ByVal uCounter As Integer)
            title = uTitle
            counter = uCounter
        End Sub
    End Class

#Region "Background - TRACK LOADING"


    Private Sub backgroundWorkerAlbums_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles backgroundWorkerAlbums.DoWork

        'Dim ListText As String
        'For Value As Integer = 0 To 100
        'If TestWorker.CancellationPending Then
        'Exit For
        'End If
        'ListText = String.Concat("Item #", Value)
        'backgroundWorkerAlbums.ReportProgress(Value, ListText)
        'Threading.Thread.Sleep(100)
        'Next

        Dim Sources As IITSourceCollection
        Dim LibSource As IITSource
        Sources = iTunesApp.Sources
        LibSource = Sources.Item(1)
        'BuildPlayLists(Sources.Item(1))

        Dim x As Integer
        Dim ab As String
        Dim counter As Integer = 0

        'Dim objPlaylist As iTunesLib.IITPlaylist
        'objPlaylist = LibPlaylists.ItemByName(playListName)

        'albumLoadProgress.Value = 0
        'albumLoadProgress.Maximum = LibSource.Playlists.Item(1).Tracks.Count)
        'albumLoadProgress.Minimum = 0
        'loadingTitle.Text = "Reading tracks..."
        'loadingPanel.Refresh()

        'todos = LibSource.Playlists.Item(1).Tracks.Count
        'backgroundWorkerAlbums.ReportProgress(todos, "reading tracks...")

        'Next
        '
        Dim thisUpdateInformation As updateStatus
        thisUpdateInformation = New updateStatus("Reading Library...", todos)
        backgroundWorkerAlbums.ReportProgress(todos, thisUpdateInformation)

        For Each Track As IITTrack In LibSource.Playlists.Item(1).Tracks
            '
            ' This next part is a personal string tidy, if a trackkindasstring has protect aac
            ' as the first part of its name then it is likely to be a purchased track so add
            ' to our own special playlist called ".Purchased"
            '
            todos += 1
            thisUpdateInformation = New updateStatus("Reading Library...", todos)
            backgroundWorkerAlbums.ReportProgress(todos, thisUpdateInformation)

            'albumLoadProgress.Value += 1
            
            '
            ' If the album has a name lowercase it for compare purposes.
            '
            If Track.Album <> Nothing Then
                ab = Track.Album.ToLower
                '
                ' Tidy up a few name odds and sods to even the comparison out
                ' Multi disc sets often have (Disc x) or [Disc x] or even a mixture
                ' of both types in the same set, this would result in each disc being
                ' placed in a separate playlist, so remove that part of the name.
                '
                If InStr(ab, "(disc") <> 0 Then
                    ab = Mid(ab, 1, InStr(ab, "(disc") - 1)
                End If

                If InStr(ab, "[") <> 0 Then
                    ab = Mid(ab, 1, InStr(ab, "[") - 1)
                End If
                '
                ' Some multidisc sets use Vol x, remove that too.
                '
                If InStr(ab, " vol") <> 0 Then
                    ab = Mid(ab, 1, InStr(ab, " vol") - 1)
                End If
                '
                ' Finally remove a few odd characters
                '
                ab = StripQuote(ab)
                ab = ab.Trim

            Else
                ab = Nothing
            End If
            '
            ' Find/Add to the album array
            '

            For x = 0 To Albums.Length
                If Albums(x).Name = Nothing Then ' End of the array, album not found add new one
                    Albums(x).Name = ab
                    Albums(x).Artist = Track.Artist
                    Albums(x).Year = Track.Year

                    ' Dim the track table in the new element to one and add the track
                    '
                    ReDim Preserve Albums(x).TrackTable(1)
                    Albums(x).TrackTable(0) = Track
                    '
                    ' Add extra element to albums
                    '
                    ReDim Preserve Albums(x + 1)
                    Exit For
                Else
                    '
                    ' If the album item is the same name as the one we are looking for add the track to its tracklist
                    '
                    If Albums(x).Name = ab Then
                        Albums(x).TrackTable(Albums(x).TrackTable.GetUpperBound(0)) = Track
                        ReDim Preserve Albums(x).TrackTable(Albums(x).TrackTable.GetUpperBound(0) + 1)
                        Exit For
                    End If
                End If
            Next

            

        Next

        'hide the loading doofa as the albums should now be visible
        'loadingPanel.Visible = False
        'loadingPanel.Visible = False
        'albumFlow.Visible = True

        'enable buttons
        'admin.Enabled = True
        'buttonPlay.Enabled = True



    End Sub

    Private Sub backgroundWorkerAlbums_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles backgroundWorkerAlbums.ProgressChanged
        albumLoadProgress.Value = e.ProgressPercentage

        Dim thisInformation As updateStatus = DirectCast(e.UserState, updateStatus)
        loadingTitle.Text = thisInformation.title
        loadingTracks.Text = thisInformation.counter & "/" & number_of_tracks
        'loadingTitle.Text = e.UserState
        'lstValues.Items.Add(e.UserState)
    End Sub

    Private Sub backgroundWorkerAlbums_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles backgroundWorkerAlbums.RunWorkerCompleted
        'btnStart.Enabled = True
        'btnCancel.Enabled = False
        'MsgBox("Loading albums done")

        'tracklisting done, so generate albums
        albumLoadProgress.Maximum = Albums.Length
        albumLoadProgress.Value = 0
        todos = 0

        backgroundWorkerCovers = New System.ComponentModel.BackgroundWorker
        backgroundWorkerCovers.WorkerReportsProgress = True
        backgroundWorkerCovers.WorkerSupportsCancellation = True
        backgroundWorkerCovers.RunWorkerAsync()

    End Sub

#End Region

#Region "background - ALBUM ART"

    Private Sub backgroundWorkerCovers_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles backgroundWorkerCovers.ProgressChanged
        albumLoadProgress.Value = e.ProgressPercentage

        Dim thisInformation As updateStatus = DirectCast(e.UserState, updateStatus)
        loadingTitle.Text = thisInformation.title
        loadingAlbumCovers.Text = thisInformation.counter & "/" & (Albums.Length - 1)

        'loadingTitle.Text = e.UserState
        'lstValues.Items.Add(e.UserState)
    End Sub

    Private Sub backgroundWorkerCovers_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles backgroundWorkerCovers.DoWork

        Dim x As Integer
        Dim myImageList As ImageList
        myImageList = New ImageList()
        Dim thisUpdateInformation As updateStatus

        '===============
        ' assign some artwork for each album we have
        '===============
        ' we want to loop through our new albub array (this is WAY quicker than doing it track by track

        'thisUpdateInformation = New updateStatus("Generating Covers...", todos)
        'backgroundWorkerCovers.ReportProgress(todos, thisUpdateInformation)
       


        For x = 0 To Albums.Length - 2

            todos += 1
            thisUpdateInformation = New updateStatus("Generating Covers...", todos)
            backgroundWorkerCovers.ReportProgress(todos, thisUpdateInformation)

            Dim Track As IITTrack
            Track = Albums(x).TrackTable(0) 'just use the first item in the array (this *should* be ok) assuming all the tracks have the same cover!

            If (My.Settings.redraw_album_covers = 1 And Track.Artwork.Item(1) IsNot Nothing) _
                    Or _
                    (System.IO.File.Exists(imagePathFullsize & Track.trackID & ".bmp") = False _
                    And Track.Artwork.Item(1) IsNot Nothing) _
                     Then

                'Try

                'loader.loaderAlbumName.Text = Track.Name


                Dim Art1 As iTunesLib.IITArtworkCollection
                Dim Art2 As iTunesLib.IITArtwork
                Art1 = Track.Artwork
                Art2 = Art1.Item(1)

                If (Track.Artwork.Count > 0) Then
                    Try
                        Art2.SaveArtworkToFile(imagePathFullsize & Track.trackID & ".png")
                        Art2 = Nothing

                        'following code resizes picture to fit
                        Dim FSimgOrig As System.IO.FileStream = New System.IO.FileStream(imagePathFullsize & Track.trackID & ".png", IO.FileMode.Open, IO.FileAccess.Read)

                        Dim bm As New Bitmap(System.Drawing.Image.FromStream(FSimgOrig))
                        Dim width As Integer = cover_width 'image width. 
                        Dim height As Integer = cover_height 'image height


                        Dim thumb As New Bitmap(width, height)
                        Dim g As Graphics = Graphics.FromImage(thumb)

                        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                        g.DrawImage(bm, New Rectangle(0, 0, width, height), New Rectangle(0, 0, bm.Width, bm.Height), GraphicsUnit.Pixel)

                        If My.Settings.use_cd_covers = 1 Then

                            'add the CD cover
                            thumb.Save(imagePathFullsize & "tmp" & Track.trackID & ".bmp", System.Drawing.Imaging.ImageFormat.Jpeg) 'can use any image format 


                            Dim mainBm As New Bitmap(135, 120)
                            Dim FStmpBmp As System.IO.FileStream = New System.IO.FileStream(imagePathFullsize & "tmp" & Track.trackID & ".bmp", IO.FileMode.Open, IO.FileAccess.Read)

                            Dim albumcoverlayer As New Bitmap(System.Drawing.Image.FromStream(FStmpBmp))
                            Dim cdcoverlayer As New Bitmap(My.Resources.cdcover) 'Image.FromFile("C:/cdcover.png"))
                            Dim mainImage As Graphics = Graphics.FromImage(mainBm)

                            'copy images onto each other
                            mainImage.DrawImage(albumcoverlayer, 13, 0)
                            mainImage.DrawImage(cdcoverlayer, 0, 0)

                            mainBm.Save(imagePathFullsize & Track.trackID & ".bmp", System.Drawing.Imaging.ImageFormat.Jpeg)

                            mainImage.Dispose()
                            mainBm.Dispose()
                            cdcoverlayer.Dispose()
                            albumcoverlayer.Dispose()
                            FStmpBmp.Close()
                            System.IO.File.Delete(imagePathFullsize & "tmp" & Track.trackID & ".bmp")

                        Else
                            thumb.Save(imagePathFullsize & Track.trackID & ".bmp", System.Drawing.Imaging.ImageFormat.Jpeg)

                        End If


                        'tidy up
                        g.Dispose()
                        bm.Dispose()
                        thumb.Dispose()

                        FSimgOrig.Close()

                        System.IO.File.Delete(imagePathFullsize & Track.trackID & ".png")

                        myImageList.Images.Add(Image.FromFile(imagePathFullsize & Track.trackID & ".bmp"))
                        Albums(x).Cover = imagePathFullsize & Track.trackID & ".bmp"

                    Catch ex As Exception
                        Albums(x).Cover = imagePathFullsize & "nocover.bmp"
                    End Try

                Else
                    'use the temporary image
                    'myImageList.Images.Add(Image.FromFile(imagePathFullsize & Track.trackID & ".bmp"))
                    Albums(x).Cover = imagePathFullsize & "nocover.bmp"
                End If

               

            Else
                'we already have an image generated for this album, so use it
                'this will hopefully save some time

                If (System.IO.File.Exists(imagePathFullsize & Track.trackID & ".bmp") = False) Then
                    'user has got here because there's no album art....
                    Albums(x).Cover = imagePathFullsize & "nocover.bmp"
                Else
                    myImageList.Images.Add(Image.FromFile(imagePathFullsize & Track.trackID & ".bmp"))
                    Albums(x).Cover = imagePathFullsize & Track.trackID & ".bmp"
                End If


            End If

            'albumLoadProgress.Value += 1
            'albumLoadProgress.Refresh()



        Next

        'so just in case we've redone all the items, change it
        If My.Settings.redraw_album_covers = 1 Then
            My.Settings.redraw_album_covers = 0
        End If

        




    End Sub

    Private Sub backgroundWorkerCovers_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles backgroundWorkerCovers.RunWorkerCompleted
        'btnStart.Enabled = True
        'btnCancel.Enabled = False
        'MsgBox("generating albums done")

        'album art done, so generate albums
        albumLoadProgress.Maximum = Albums.Length
        albumLoadProgress.Value = 0
        todos = 0

        backgroundWorkerDrawer = New System.ComponentModel.BackgroundWorker
        backgroundWorkerDrawer.WorkerReportsProgress = True
        backgroundWorkerDrawer.WorkerSupportsCancellation = True
        backgroundWorkerDrawer.RunWorkerAsync()

    End Sub


#Region "background - DRAW COVERS TO SCREEN"

    Private Sub backgroundWorkerDrawer_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles backgroundWorkerDrawer.ProgressChanged
        albumLoadProgress.Value = e.ProgressPercentage

        Dim thisInformation As updatePanels = DirectCast(e.UserState, updatePanels)
        loadingTitle.Text = thisInformation.title
        loadingDrawCovers.Text = thisInformation.counter & "/" & (Albums.Length - 1)
        albumFlow.Controls.Add(thisInformation.newPanel)

    End Sub

    Private Sub backgroundWorkerDrawer_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles backgroundWorkerDrawer.RunWorkerCompleted
        'btnStart.Enabled = True
        'btnCancel.Enabled = False
        'MsgBox("generating albums done")

        'tracklisting done, so generate albums
        'albumLoadProgress.Maximum = Albums.Length
        'albumLoadProgress.Value = 0
        'todos = 0

        'backgroundWorkerCovers = New System.ComponentModel.BackgroundWorker
        'backgroundWorkerCovers.WorkerReportsProgress = True
        'backgroundWorkerCovers.WorkerSupportsCancellation = True
        'backgroundWorkerCovers.RunWorkerAsync()

        System.Threading.Thread.Sleep(750) 'delay by a second so we can see a little of what's been done

        loadingPanel.Visible = False
        albumFlow.Visible = True
        admin.Enabled = True
        buttonPlay.Enabled = True

    End Sub

    Private Class updatePanels
        Public newPanel As Panel
        Public title As String
        Public counter As Integer

        Public Sub New(ByVal uPanel As Panel, ByVal uTitle As String, ByVal uCounter As Integer)
            newPanel = uPanel
            title = uTitle
            counter = uCounter
        End Sub
    End Class

    Private Sub backgroundWorkerDrawer_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles backgroundWorkerDrawer.DoWork

        Dim ab As String

        'loadingTitle.Text = "Drawing album list..."
        'loadingPanel.Refresh()

        '=================== 
        'try to speed things up and do the spacing calculations here before the loop

        Dim num_albums_across As Decimal = _
            Fix((albumFlow.Width - 50) / (cover_width + 20)) 'we always have 10 padding each side of the cover art and 50 for the scroller

        Dim cover_panel_width As Integer = (albumFlow.Width - 50) / num_albums_across
        Dim thisUpdateInformation As updatePanels

        'backgroundWorkerDrawer.ReportProgress(todos, "Drawing covers...")

        For i = 0 To Albums.Length - 2
            '
            ' See if Artist Name is Same For Every Track in the List
            ' if it is prefix the album name with the artist name
            '

            

            ab = Albums(i).TrackTable(0).Artist

            'For x = 0 To Albums(i).TrackTable.Length - 2
            'If ab <> Albums(i).TrackTable(x).Artist Then
            'ab = ""

            'Exit For
            'End If
            'Next
            '
            ' Some artist names are huge (orchestra, conductor, lead singer and his wife)
            ' Shorten long ones to nearest comma.
            '
            If ab.Length > 30 Then
                If InStr(ab, ",") > 0 Then
                    ab = Mid(ab, 1, InStr(ab, ",") - 1)
                Else
                    ab = ""
                End If
            End If
            '
            ' If we have an artist name add a hyphen
            '
            'If ab <> "" Then
            'ab += " - "
            'End If

            '
            ' Display the album covers
            '

            Dim panel As New Panel()

            panel.Size = New Size(cover_panel_width, (cover_height + 60))

            'panel.BackgroundImage = My.Resources.shadow
            'panel.BackgroundImageLayout = ImageLayout.Center


            'album shadow
            'Dim picShadow As New PictureBox()
            'picShadow.Size = New Size(153, 138)
            'picShadow.Location = New Point(4, 0)
            'picShadow.BackColor = Color.Transparent
            'picShadow.Image = My.Resources.shadow

            'album cover
            Dim pic As New PictureBox()
            pic.Size = New Size(cover_width, cover_height)
            pic.Location = New Point(10, 10)
            'If (Albums(i).Cover = "nocover") Then
            'pic.Image = Image.FromFile(Albums(i).Cover)
            'Else
            pic.Image = Image.FromFile(Albums(i).Cover)
            'End If
            pic.Tag = i
            pic.BorderStyle = BorderStyle.FixedSingle
            AddHandler pic.Click, AddressOf album_Click



            'title label
            Dim label0 As New AntialiasedLabel()
            label0.Size = New Size(cover_width, 15)
            label0.Location = New Point(10, (cover_height + 15))
            label0.TextAlign = ContentAlignment.TopCenter
            label0.AutoEllipsis = True
            label0.Font = New Font(label0.Font.FontFamily, 8, FontStyle.Bold)
            'label0.Parent = picShadow
            label0.BackColor = Color.Transparent
            label0.ForeColor = Color.White
            label0.Text = StrConv(Albums(i).Name, VbStrConv.ProperCase)

            'artist label
            Dim label1 As New AntialiasedLabel()
            label1.Size = New Size(cover_width, 15)
            label1.Location = New Point(10, (cover_height + 30))
            label1.TextAlign = ContentAlignment.TopCenter
            label1.AutoEllipsis = True
            label1.BackColor = Color.Transparent
            label1.ForeColor = Color.White
            label1.Text = StrConv(Albums(i).Artist, VbStrConv.ProperCase)

            'panel.Controls.Add(cdcover)
            panel.Controls.Add(label0)
            panel.Controls.Add(label1)
            panel.Controls.Add(pic)
            'panel.Controls.Add(picShadow)


            todos += 1
            thisUpdateInformation = New updatePanels(panel, "Drawing Albums...", todos)
            backgroundWorkerDrawer.ReportProgress(todos, thisUpdateInformation)

           

            'backgroundWorkerDrawer.ReportProgress(todos, "Drawing covers...")

        Next
       


    End Sub

#End Region


    Public Sub check_start_up()

        'this will check if it's the first time this has been loaded
        If System.IO.Directory.Exists(appDataPath & "\" & appTitleForPath) = False Then

            'MsgBox("It looks like this is the first time you've run iTunesTouch" & vbNewLine & "" & vbNewLine & "It make take a minute or so to generate the album art.. so please be patient")

            'create the folders required for this app
            '\iTunesTouch\albumart\fullsize\
            '\iTunesTouch\albumart\thumbs\
            Try
                System.IO.Directory.CreateDirectory(appDataPath & "\" & appTitleForPath)
                System.IO.Directory.CreateDirectory(imagePathFullsize)
                System.IO.Directory.CreateDirectory(imagePathThumbs)
            Catch ex As Exception
                MsgBox("Looks like there was a problem when creating the albumart directories, so exiting")
                Application.Exit()
            End Try
        End If

        'we will always show this progress bar as the user could have run this several months ago
        'and have added WAY more music so that would cause a delay....




    End Sub

    Public Sub generate_no_cd_cover()

        '==== generate the no cd cover art image (based on the cover size the user specifies)
        'Dim FSimgOrig As System.IO.FileStream = New System.IO.FileStream(imagePathFullsize & Track.trackID & ".png", IO.FileMode.Open, IO.FileAccess.Read)

        Dim bm As New Bitmap(My.Resources.nocdlarge)
        Dim width As Integer = cover_width 'image width. 
        Dim height As Integer = cover_height 'image height

        Dim thumb As New Bitmap(width, height)
        Dim g As Graphics = Graphics.FromImage(thumb)

        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(bm, New Rectangle(0, 0, width, height), New Rectangle(0, 0, bm.Width, bm.Height), GraphicsUnit.Pixel)

        thumb.Save(imagePathFullsize & "nocover.bmp", System.Drawing.Imaging.ImageFormat.Jpeg) 'can use any image format 

        g.Dispose()
        thumb.Dispose()
        bm.Dispose()


    End Sub

#End Region




#Region "playlist"

    Public Sub loadPlaylist_iTunesDJ()

        Dim Source As IITSourceCollection = iTunesApp.Sources
        Dim PlayList As iTunesLib.IITPlaylist = Nothing
        Dim i As Integer
        'My.Settings.playlist = "iTunes DJ"

        labelPlaylist.Text = "Playlist: " & playListName









        'first let's clear the list
        playlistFlow.Controls.Clear()

        '
        ' Update listview of tracks to display selected playlists tracks
        '

        'For i = 1 To Source.Count
        Try
            PlayList = Source.Item(1).Playlists.ItemByName(playListName)

            If Not PlayList Is Nothing Then
                '
                ' Found it
                '
            End If
        Catch ex As Exception
            MsgBox("Error loading playlist: " & My.Settings.playlist)
            PlayList = Nothing
        End Try


        'setup the list to use small icons

        Dim myImageList As ImageList
        myImageList = New ImageList()
        myImageList.ColorDepth = ColorDepth.Depth32Bit

        Dim y As Integer = 0


        '
        ' If PlayLists is valid we found playlist, display its tracks
        '
        If Not PlayList Is Nothing Then

            'Dim lv As ListViewItem
            Dim z As Integer = 0
            For Each Track As iTunesLib.IITTrack In PlayList.Tracks

                '
                ' Build listviewitem for the track
                '

                If z > 0 Then
                    'this should skip the first record which is our now playing one

                    Dim panel As New Panel()
                    panel.Size = New Size(180, 30)
                    'panel.BackgroundImage = Image.FromFile("C:/playlistbg.png")
                    'panel.BackgroundImageLayout = ImageLayout.Stretch


                    'album cover
                    'Dim pic As New PictureBox()
                    'pic.Size = New Size(40, 40)
                    'pic.Location = New Point(8, 8)
                    'pic.Image = myImageList.Images(z)
                    'pic.Tag = i
                    'AddHandler pic.Click, AddressOf album_Click

                    'title label
                    Dim label0 As New AntialiasedLabel()
                    label0.Size = New Size(190, 15)
                    label0.Location = New Point(5, 0)
                    label0.TextAlign = ContentAlignment.TopLeft
                    label0.AutoEllipsis = True
                    label0.Font = New Font(label0.Font.FontFamily, 9)
                    label0.BackColor = Color.Transparent
                    label0.ForeColor = Color.White
                    label0.Text = StrConv(Track.Name, VbStrConv.ProperCase)

                    'artist label
                    Dim label1 As New AntialiasedLabel()
                    label1.Size = New Size(190, 15)
                    label1.Location = New Point(5, 15)
                    label1.TextAlign = ContentAlignment.TopLeft
                    label1.Font = New Font(label1.Font.FontFamily, 8)
                    label1.AutoEllipsis = True
                    label1.BackColor = Color.Transparent
                    label1.ForeColor = Color.Gainsboro
                    label1.Text = StrConv(Track.Artist, VbStrConv.ProperCase)

                    'time label
                    'Dim label2 As New AntialiasedLabel()
                    'label2.Size = New Size(190, 15)
                    'label2.Location = New Point(5, 30)
                    'label2.TextAlign = ContentAlignment.TopLeft
                    'label2.AutoEllipsis = True
                    'label2.Font = New Font(label2.Font.FontFamily, 8)
                    'label2.BackColor = Color.Transparent
                    'label2.ForeColor = Color.Gainsboro
                    'label2.Text = Track.Time

                    'panel.Controls.Add(pic)
                    'panel.Controls.Add(picShadow)
                    panel.Controls.Add(label0)
                    panel.Controls.Add(label1)
                    'panel.Controls.Add(label2)


                    playlistFlow.Controls.Add(panel)


                End If
                z = (z + 1)
                'update the list so we can see the items being added??


            Next

        End If

        'update the scroller
        playlistFlow.VerticalScroll.Minimum = 0
        playlistFlow.VerticalScroll.Maximum = playlistFlow.VerticalScroll.Maximum


    End Sub

    Public Sub updatePlaylist_itunesDJ()

        '
        ' this update function will simply add on an item to the end of the playlist
        '

        Dim Track As IITTrack

        'set the scrollbar to the bottom so it's ready
        playlistFlow.Focus()
        playlistFlow.VerticalScroll.Value = playlistFlow.VerticalScroll.Maximum
        playlistFlow.VerticalScroll.Minimum = 0
        playlistFlow.VerticalScroll.Maximum = playlistFlow.VerticalScroll.Maximum


        Track = Albums(selectedAlbum).TrackTable(selectedTrack)



        Dim panel As New Panel()
        panel.Size = New Size(180, 30)
        'panel.BackgroundImage = Image.FromFile("C:/playlistbg.png")
        'panel.BackgroundImageLayout = ImageLayout.Stretch


        'album cover
        'Dim pic As New PictureBox()
        'pic.Size = New Size(40, 40)
        'pic.Location = New Point(8, 8)
        'pic.Image = myImageList.Images(z)
        'pic.Tag = i
        'AddHandler pic.Click, AddressOf album_Click

        'title label
        Dim label0 As New AntialiasedLabel()
        label0.Size = New Size(190, 15)
        label0.Location = New Point(5, 0)
        label0.TextAlign = ContentAlignment.TopLeft
        label0.AutoEllipsis = True
        label0.Font = New Font(label0.Font.FontFamily, 9)
        label0.BackColor = Color.Transparent
        label0.ForeColor = Color.White
        label0.Text = StrConv(Track.Name, VbStrConv.ProperCase)

        'artist label
        Dim label1 As New AntialiasedLabel()
        label1.Size = New Size(190, 15)
        label1.Location = New Point(5, 15)
        label1.TextAlign = ContentAlignment.TopLeft
        label1.Font = New Font(label1.Font.FontFamily, 8)
        label1.AutoEllipsis = True
        label1.BackColor = Color.Transparent
        label1.ForeColor = Color.Gainsboro
        label1.Text = StrConv(Track.Artist, VbStrConv.ProperCase)

        'time label
        'Dim label2 As New AntialiasedLabel()
        'label2.Size = New Size(190, 15)
        'label2.Location = New Point(5, 30)
        'label2.TextAlign = ContentAlignment.TopLeft
        'label2.AutoEllipsis = True
        'label2.Font = New Font(label2.Font.FontFamily, 8)
        'label2.BackColor = Color.Transparent
        'label2.ForeColor = Color.Gainsboro
        'label2.Text = Track.Time

        'panel.Controls.Add(pic)
        'panel.Controls.Add(picShadow)
        panel.Controls.Add(label0)
        panel.Controls.Add(label1)
        'panel.Controls.Add(label2)




        playlistFlow.Controls.Add(panel)
        'playlistFlow.VerticalScroll.Maximum = (playlistFlow.VerticalScroll.Maximum + 50)
        playlistFlow.VerticalScroll.Value = playlistFlow.VerticalScroll.Maximum

    End Sub

    Public Sub reset_selected_rows()

        '===========
        ' function to reset the track lists from when they are selected
        '===========

        For x = 0 To popupTrackFlow.Controls.Count() - 1
            'popupTrackFlow.Controls.Item(x).Controls.Item(0).Location = New Point(10, 0)
            'popupTrackFlow.Controls.Item(x).BackgroundImage = Image.FromFile("C:/tracklistbg.png")
            'popupTrackFlow.Controls.Item(x).BackgroundImageLayout = ImageLayout.Tile
            popupTrackFlow.Controls.Item(x).BackColor = Color.Transparent
        Next

    End Sub

    Public Sub playFirstSongInPlaylist()

        'this will force the player in to playing the first in our newly selected playlist
        Dim objPlaylist As iTunesLib.IITPlaylist
        objPlaylist = LibPlaylists.ItemByName(playListName)

        If objPlaylist.Tracks.Count > 0 Then
            'pick a song
            objPlaylist.Tracks.Item(1).Play()
            buttonPlay.Text = "PAUSE"
        Else
            MsgBox("There are no tracks in the playlist. Please add one!")
        End If

    End Sub

#End Region



#Region "updaters"

    Function iPos()
        Try
            If iTunesApp.PlayerState <> ITPlayerState.ITPlayerStateStopped Then
                Dim length = iTunesApp.PlayerPosition, hrs, mins, secs
                hrs = Math.Floor(length / 3600)
                length = length - (hrs * 3600)
                mins = Math.Floor(length / 60)
                length = length - (mins * 60)
                secs = length
                If hrs = 0 Then
                    Return Format(mins, "#0") & ":" & Format(secs, "00")
                Else
                    Return hrs & ":" & Format(mins, "00") & ":" & Format(secs, "00")
                End If
            Else
                Return "--:--/--:--"
            End If

        Catch ex As Exception
            MsgBox("Error updating time position. Couldn't find itunes? Try closing and reopening")
            Return "--:--/--:--"
        End Try

    End Function

    Function updateTr()
        Try
            Dim cTrack As IITTrack = iTunesApp.CurrentTrack
            If iTunesApp.PlayerState <> ITPlayerState.ITPlayerStateStopped Then
                nowPlayingAlbumName.Text = StrConv(cTrack.Album, VbStrConv.ProperCase)
                nowPlayingTrackName.Text = StrConv(cTrack.Name, VbStrConv.ProperCase)
                nowPlayingArtistName.Text = StrConv(cTrack.Artist, VbStrConv.ProperCase)
                nowPlayingTrackTime.Text = iPos() & "/" & cTrack.Time

                Dim str As String = cTrack.Album
                Dim sb As New System.Text.StringBuilder
                Dim illegalChars As Char() = " !@#$%^&*(){}[]""_+<>?/".ToCharArray()

                For Each ch As Char In str
                    If Array.IndexOf(illegalChars, ch) = -1 Then
                        sb.Append(ch)
                    End If
                Next

                Dim albumNameClean As String = sb.ToString()
                If System.IO.File.Exists(imagePathThumbs & albumNameClean & ".bmp") Then
                    nowPlayingCoverArt.Image = Image.FromFile(imagePathThumbs & albumNameClean & ".bmp")
                Else
                    If cTrack.Artwork.Item(1) IsNot Nothing Then
                        do_nowplaying_art(cTrack)
                        nowPlayingCoverArt.Image = Image.FromFile(imagePathThumbs & albumNameClean & ".bmp")
                    Else
                        nowPlayingCoverArt.Image = My.Resources.nocdsmall 'Image.FromFile(appPath & "thumb_nocover.png")
                    End If
                End If


            Else
                nowPlayingAlbumName.Text = "..."
                nowPlayingTrackName.Text = "..."
                nowPlayingArtistName.Text = "..."
                nowPlayingTrackTime.Text = "--:--/--:--"
                nowPlayingCoverArt.Image = My.Resources.nocdsmall 'Image.FromFile(appPath & "thumb_nocover.png")
            End If
            Return True

        Catch ex As Exception

            'MsgBox("Error connecting to itunes, try opening and closing again, sorry")
            nowPlayingAlbumName.Text = "..."
            nowPlayingTrackName.Text = "..."
            nowPlayingArtistName.Text = "..."
            nowPlayingTrackTime.Text = "--:--/--:--"
            nowPlayingCoverArt.Image = My.Resources.nocdsmall 'Image.FromFile(appPath & "thumb_nocover.png")
            Return True

        End Try

    End Function

    Private Sub timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer.Tick




        Try
            Dim cTrackCheck As IITTrack = iTunesApp.CurrentTrack
            If iTunesApp.PlayerState <> ITPlayerState.ITPlayerStateStopped Then
                Try


                    If iPos() <> iTunesApp.CurrentTrack.Time Or iPos() <> "0:01" Then
                        nowPlayingTrackTime.Text = iPos() & "/" & iTunesApp.CurrentTrack.Time
                    End If

                    'Dim Title = Split(Me.Text, "-")
                    If nowPlayingTrackName.Text.ToLower <> cTrackCheck.Name.ToLower Then
                        updateTr()
                        loadPlaylist_iTunesDJ() 'refresh the playlist
                    End If

                Catch ex As Exception
                    'MsgBox("There was an error connecting to iTunes.\nTry playing a track in iTunes then loading the touch interface")
                End Try

                'update the button as it must be playing!
                buttonPlay.Text = "PAUSE"
            Else
                buttonPlay.Text = "RESUME"
            End If

        Catch ex As Exception
            'don't show anything otherwise there could be a million warnings!
        End Try

    End Sub

    Public Sub do_nowplaying_art(ByVal track As IITTrack)

        'album 
        Dim str As String = track.Album
        Dim sb As New System.Text.StringBuilder
        Dim illegalChars As Char() = " !@#$%^&*(){}[]""_+<>?/".ToCharArray()

        For Each ch As Char In str
            If Array.IndexOf(illegalChars, ch) = -1 Then
                sb.Append(ch)
            End If
        Next

        Dim albumNameClean As String = sb.ToString()

        Dim Art1 As iTunesLib.IITArtworkCollection
        Dim Art2 As iTunesLib.IITArtwork
        Art1 = track.Artwork
        Art2 = Art1.Item(1)
        Art2.SaveArtworkToFile(imagePathThumbs & albumNameClean & ".png")
        Art2 = Nothing


        'following code resizes picture to fit
        Dim FSimgOrig As System.IO.FileStream = New System.IO.FileStream(imagePathThumbs & albumNameClean & ".png", IO.FileMode.Open, IO.FileAccess.Read)

        'following code resizes picture to fit
        Dim bm As New Bitmap(System.Drawing.Image.FromStream(FSimgOrig))
        Dim width As Integer = 60 'image width. 
        Dim height As Integer = 60 'image height
        Dim thumb As New Bitmap(width, height)
        Dim g As Graphics = Graphics.FromImage(thumb)

        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(bm, New Rectangle(0, 0, width, height), New Rectangle(0, 0, bm.Width, bm.Height), GraphicsUnit.Pixel)
        g.Dispose()

        'image path. better to make this dynamic. I am hardcoding a path just for example sake
        thumb.Save(imagePathThumbs & albumNameClean & ".bmp", System.Drawing.Imaging.ImageFormat.Jpeg) 'can use any image format 

        'tidy up
        bm.Dispose()
        thumb.Dispose()

        FSimgOrig.Close()
        System.IO.File.Delete(imagePathThumbs & albumNameClean & ".png")

    End Sub

#End Region


#Region "track events"

    Public Sub track_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim label0 As Label = DirectCast(sender, Label)
        'Dim panel As Panel
        'Dim tick As PictureBox

        selectedTrack = label0.Tag

        'no others should be selected, so reset ALL the rows in the table
        reset_selected_rows()

        label0.Parent.BackColor = Color.LightGray
        'label0.Location = New Point(35, 0)
        'label0.Parent.BackgroundImage = Image.FromFile("C:/tracklistbgSelected.png")
        'label0.Parent.BackgroundImageLayout = ImageLayout.None

        addTrackToPlaylist.Visible = True

    End Sub

    Private Sub addTrackToPlaylist_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addTrackToPlaylist.Click
        '
        ' add the selected track to the itunes DJ playlist
        '
        Dim PlayList As iTunesLib.IITPlaylist = Nothing
        Dim Source As IITSourceCollection = iTunesApp.Sources
        Dim i As Integer

        For i = 1 To Source.Count
            Try
                PlayList = Source.Item(i).Playlists.ItemByName(playListName)
                If Not PlayList Is Nothing Then
                    '
                    ' Found it
                    '
                    Exit For
                End If
            Catch ex As Exception
                MsgBox("Error adding to playlist: " & playListName)
                PlayList = Nothing
            End Try
        Next

        If Not PlayList Is Nothing Then
            'add the selected track to the playlist
            Dim playlistcount = PlayList.Tracks.Count()
            PlayList.AddTrack(Albums(selectedAlbum).TrackTable(selectedTrack))
            Dim playlistcountNOW = PlayList.Tracks.Count()
            If (playlistcountNOW > playlistcount) Then
                updatePlaylist_itunesDJ()
            Else
                MsgBox("Song already exists in the playlist")
            End If
            addTrackToPlaylist.Visible = False
            'reset the selected rows
            reset_selected_rows()
        End If
    End Sub


    Private Sub popupClosebutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles popupClosebutton.Click
        trackPanel.Visible = False
    End Sub


#End Region



#Region "album functions"

    Public Sub album_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim cdcover As PictureBox = DirectCast(sender, PictureBox)
        selectedAlbum = cdcover.Tag

        popupTrackFlow.Controls.Clear()
        If (Albums(selectedAlbum).Year > 0) Then
            popupAlbumYear.Text = Albums(selectedAlbum).Year
        Else
            popupAlbumYear.Text = ""
        End If

        popupAlbumArtist.Text = StrConv(Albums(selectedAlbum).Artist, VbStrConv.ProperCase)
        popupAlbumName.Text = StrConv(Albums(selectedAlbum).Name, VbStrConv.ProperCase)


        'popupCover.ImageLocation = Albums(selectedAlbum).Cover

        For x = 0 To Albums(selectedAlbum).TrackTable.Length - 2

            Dim panel As New Panel()
            panel.Size = New Size(230, 20)
            'panel.BackgroundImage = Image.FromFile("C:/tracklistbg.png")
            'panel.BackgroundImageLayout = ImageLayout.Tile


            'tick
            'Dim tick As New PictureBox()
            'tick.Size = New Size(20, 23)
            'tick.Location = New Point(4, 0)
            'tick.BackColor = Color.Transparent
            'tick.Image = Image.FromFile("C:/tick.png")
            'tick.Tag = "tick" & x
            'tick.Visible = False
            'tick.Parent = panel

            'track label
            Dim label0 As New AntialiasedLabel()
            label0.Size = New Size(230, 20)
            label0.Location = New Point(0, 0)
            label0.TextAlign = ContentAlignment.MiddleLeft
            label0.AutoEllipsis = True
            label0.Font = New Font(label0.Font.FontFamily, 8)
            label0.BackColor = Color.Transparent
            label0.ForeColor = Color.Black
            label0.Text = StrConv(Albums(selectedAlbum).TrackTable(x).Name, VbStrConv.ProperCase)
            label0.Tag = x
            AddHandler label0.Click, AddressOf track_Click

            'panel.Controls.Add(tick)
            panel.Controls.Add(label0)


            popupTrackFlow.Controls.Add(panel)



        Next


        trackPanel.Visible = True



    End Sub

#End Region



#Region "button events"

    Private Sub buttonPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonPlay.Click
        If buttonPlay.Text = "PAUSE" Then
            iTunesApp.Pause()
            buttonPlay.Text = "RESUME"
        ElseIf buttonPlay.Text = "RESUME" Then
            Try
                If iTunesApp.PlayerState = ITPlayerState.ITPlayerStateStopped _
                    And iTunesApp.PlayerPosition < 1 Then
                End If
            Catch ex As Exception
                'there is no track playing, so try and get one from the playlist
                Dim objPlaylist As iTunesLib.IITPlaylist
                'Dim lvi As ListView.SelectedListViewItemCollection
                '
                ' Find PlayList
                '
                objPlaylist = LibPlaylists.ItemByName(playListName)

                If objPlaylist.Tracks.Count > 0 Then
                    'pick a song
                    objPlaylist.Tracks.Item(1).Play()
                    buttonPlay.Text = "PAUSE"
                Else
                    MsgBox("There are no tracks in the playlist. Please add one!")
                End If
            End Try

            Try
                If iTunesApp.PlayerState = ITPlayerState.ITPlayerStateStopped _
                    And iTunesApp.PlayerPosition > 0 Then
                    iTunesApp.Play()
                    buttonPlay.Text = "PAUSE"
                End If
            Catch ex As Exception
                MsgBox("Playing error. Please try starting the application again")
            End Try

        End If

    End Sub

    'Sub slVolume_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles slVolume.Scroll
    '    iTunesApp.SoundVolume = slVolume.Value
    'End Sub





#End Region



#Region "string functions"

    Public Function StripQuote(ByVal Source As String) As String
        Dim strX As New StringBuilder(Source)
        '

        ' Remove a few character types from

        ' the album name string passed as argument

        ' Some multi CD albums do not stick

        ' to the same naming convention, the characters

        ' stripped here are one or two I have

        ' notice in my own albums, you may find more

        ' and add them as you wish to make your

        ' lists tidier. Personally the person who

        ' created the album names in the online

        ' database should be punished for every variation

        ' in the naming of CD's in an album set.

        '

        strX.Replace("!", "")
        strX.Replace("'", "")
        strX.Replace("`", "")
        strX.Replace("�", "")
        strX.Replace(" - ", " ")
        strX.Replace("...", " ")

        StripQuote = strX.ToString
    End Function

#End Region

    Private Sub admin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles admin.Click
        Dim pinForm As New pin()
        pinForm.Show()

    End Sub

    'Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    '    iTunesApp = Nothing
    '    Application.Exit()
    'End Sub
End Class
